#!/usr/bin/perl

use PGPLOT;
use lib '/data/MENTOK_2/ste616/EB500/Software/Utilities/TCPExample';
use ATNF::MoniCA;
use ATNF::Credentials qw($user $pass);
use strict;

my $rdir = "/data/MENTOK_2/ste616/EB500/Software/Utilities/TCPExample";

# Check that we are allowed to move the rotator.
if (&antenna_movable() == 0) {
    die "Not allowed to move the rotator.";
}

# Wait until we are allowed to use the EB500.
my $ntries = 0;
while (&eb500_reserved() == 1 && $ntries < 30) {
    $ntries++;
    sleep 1;
}
if (&eb500_reserved() == 1) {
    die "Not allowed to use EB500.";
}

# Reserve the EB500.
&reserve_eb500();

# Reserve the antenna if we can.
if (&antenna_reserved() == 1) {
    &release_eb500();
    die "Antenna is allocated to someone else.";
}

&reserve_antenna();

# Connect to MoniCA so we can control the rotator.
my $mon = monconnect("monhost-nar");

# Get the current time and make a directory to hold the results.
chomp(my $tdate = `date -I'minutes'`);
my $tdir = $rdir."/".$tdate;

mkdir $tdir;
chdir $tdir;

# Move the antenna around in 10 degree increments.
for (my $i = 0; $i < 360; $i += 10) {
    &moveantenna($i + 0.2);
    &runscan($i);
}

# Release the EB500.
&release_eb500();

# Generate the plots.
system "python ../plot_rfisky.py > plotname.out";

# Assign it as the current plot.
chomp(my $pname = `cat plotname.out`);
system "cp ".$pname." /n/ste616/Documents/rfi_skyplots/skyplot_latest.png";

# Move the antenna back to North, ready for the next run.
&moveantenna(180);
&moveantenna(90);
#&moveantenna(0.2);

# Release the antenna.
&release_antenna();

sub runscan {
    # Get the data from the EB500.
    my $currloc = shift;

    system $rdir."/rfiplot > /dev/null";

    chomp(my $d = `date -u -I'seconds'`);
    my $rsc = sprintf "cp rfi_spectrum.txt ../spectra/rfispectrum_".$d.".txt";
    system $rsc;
    $rsc = sprintf "mv rfi_spectrum.txt rfispectrum_%03d.txt",
    $currloc;
    system $rsc;
}

sub moveantenna {
    # Move the rotator to a position and wait for it to get there.
    my $newloc = shift;

    # Check again that we are allowed to move the rotator.
    if (&antenna_movable == 0) {
	print "Not allowed to move rotator to $newloc degrees.\n";
	sleep 10;
	return;
    }

    my @setpoints;
    
    push @setpoints, new MonSetPoint(
	{
	    point => "site.misc.rfirotator.control.Az",
	    val => $newloc,
	    type => "flt"
	});
    my @r = monset_m($mon, $user, $pass,
		     2, @setpoints);
    
    my $mp = "site.misc.rfirotator.Az";
    
    my $ce = 0;
    my $ntries = 0;
    while ($ce == 0 && $ntries < 60) {
	my $p = monpoll2($mon, $mp);
	my $d = abs($p->val - $newloc);
	if ($d < 1) {
	    $ce = 1;
	}
	$ntries++;
	sleep 1;
    }
    if ($ntries >= 60) {
	&release_antenna();
	&release_eb500();
	die "Antenna not responding.\n";
    }

    return;
}

sub antenna_movable {
    # Check whether we have permission to move the rotator.
    chomp(my $movable = `cat $rdir/.antenna_movable`);
    
    if ($movable eq "true") {
	return 1;
    } else {
	return 0;
    }
}

sub reserve_antenna {
    # Prevent other users from rotating the antenna.
    open(F, ">".$rdir."/.rotator_reserved");
    print F "true";
    close(F);
}

sub release_antenna {
    # Allow other users to rotate the antenna.
    open(F, ">".$rdir."/.rotator_reserved");
    print F "false";
    close(F);
}

sub antenna_reserved {
    # Check whether the antenna is reserved.
    chomp(my $reserved = `cat $rdir/.rotator_reserved`);
    
    if ($reserved eq "false") {
	return 0;
    } else {
	return 1;
    }
}

sub reserve_eb500 {
    # Prevent other users from calling the EB500.
    open(F, ">".$rdir."/.eb500_reserved");
    print F "true";
    close(F);
}

sub release_eb500 {
    # Allow other users to calling the EB500.
    open(F, ">".$rdir."/.eb500_reserved");
    print F "false";
    close(F);
}

sub eb500_reserved {
    # Check whether the EB500 is reserved.
    chomp(my $reserved = `cat $rdir/.eb500_reserved`);
    
    if ($reserved eq "false") {
	return 0;
    } else {
	return 1;
    }
}
